package com.tfy.liquor.util;

import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.util.ArrayList;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 文件类工具
 */
public class FileUtil {
    private final static Logger logger = LoggerFactory.getLogger(FileUtil.class);

    // 获取文件后缀名称
    public static String getFileSuffix(MultipartFile file) {
        if (file == null) {
            return null;
        }
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        int suffixIndex = fileName.lastIndexOf(".");
        if (suffixIndex == -1) {    // 无后缀
            return null;
        } else {                    // 存在后缀
            return fileName.substring(suffixIndex, fileName.length());
        }
    }

    /**
     * 上传文件并保存到文件，然后返回文件路径信息
     */
    public static String upLoadFile(MultipartFile file, String path) throws IOException {
//        Map<String, Object> map = new HashMap<String, Object>();
        //使用UUID给图片重命名，并去掉四个“-”
        String name = UUID.randomUUID().toString().replaceAll("-", "");
        //获取文件的扩展名
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        //设置图片上传路径
        //获取项目根路径下面自己新建的upload123文件夹，用于存储图片
//        String url = request.getSession().getServletContext().getRealPath("/");
//        path += "images";
        File filex = new File(path);
        if (!filex.exists()) {
            filex.mkdir();
        }
        //以绝对路径保存重名命后的图片
        file.transferTo(new File(path + File.separator + name + "." + ext));
//        System.err.println(url);
        logger.info("上传图片：" + path + File.separator + name + "." + ext);
        return name + "." + ext;
    }

    /**
     * 将富文本中的base64图片转为图片文件并保存
     */
    public static String getImgSrc(String htmlStr) {
        String img = "";
        Pattern p_image;
        Matcher m_image;
        ArrayList<String> pics = new ArrayList();
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            img = img + "," + m_image.group();
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
                // 打印解析的信息
//                System.err.println(m.group(1));
                // 将base64编码转为图片信息
                if (m.group(1).startsWith("data:image/")) {
                    String fileName = null;
                    try {
                        fileName = GenerateImage(m.group(1), "/www/wwwroot/images");
                    } catch (Exception e) {
                        logger.error("保存base64文件失败：" + e.getMessage());
                    }
                    // 将保存后的图片名称保存到富文本原始数据中
                    assert fileName != null;
                    htmlStr = htmlStr.replaceAll(m.group(1), fileName);
                }
            }
        }
        return htmlStr;
    }


    /**
     * base64字符串转化成图片
     *
     * @param imgStr    base64编码
     * @param imagePath 文件保存路径
     * @return
     * @throws Exception
     */
    private static String GenerateImage(String imgStr, String imagePath) throws Exception {
        //对字节数组字符串进行Base64解码并生成图片
        //使用UUID给图片重命名，并去掉四个“-”
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        String filePath = imagePath + File.separator + fileName + ".jpg";
        BASE64Decoder decoder = new BASE64Decoder();
        //Base64解码
        imgStr = imgStr.substring(imgStr.indexOf("base64,") + 7);
        byte[] b = decoder.decodeBuffer(imgStr);
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {//调整异常数据
                b[i] += 256;
            }
        }
        //生成jpeg图片
//        fileHelper.createNewFile(filePath);
        File filex = new File(imagePath);
        if (!filex.exists()) {
            filex.mkdir();
        }
        OutputStream out = new FileOutputStream(filePath);
        out.write(b);
        out.flush();
        out.close();
        return fileName + ".jpg";
    }


}
